<template>
  <div class="mapbox" v-show="changeDeagle" >
<!--  右侧关闭  -->
    <div style="position: absolute;right: 10px;top: 10px;z-index: 200;color: #FFFFFF;font-size: 16px">
      <Icon type="md-close"  @click="changeDeagle=false"  />
    </div>


    <Button type="primary" shape="circle"  style="position: absolute;left: 10px;top:10px;z-index: 200" @click="tableShow=!tableShow">
      <Icon type="md-arrow-back" v-show="!tableShow"  />
      <Icon type="md-arrow-forward" v-show="tableShow" />
    </Button>

    <Button type="primary" shape="circle" :disabled="!(leftTable&&rightTable)" style="position: absolute;left: 60px;top:10px;z-index: 200" @click="changeRange">
      <i class="fa fa-arrows-h" v-show="leftTop"></i>
      <i class="fa fa-arrows-v" v-show="!leftTop"></i>
    </Button>

    <Button type="primary" shape="circle"  style="position: absolute;left: 130px;top:10px;z-index: 200"    @click="showMap('left')"  >
      <i class="fa fa-arrow-left"></i>
    </Button>

    <Button type="primary" shape="circle"  style="position: absolute;left: 180px;top:10px;z-index: 200"    @click="showMap('center')"  >
      <i class="fa fa-stop-circle"></i>
    </Button>

    <Button type="primary" shape="circle"  style="position: absolute;left: 230px;top:10px;z-index: 200"    @click="showMap('right')"  >
      <i class="fa fa-arrow-right"></i>
    </Button>


<!-- 树结构  -->
    <div v-show="tableShow" style="display: flex;flex-direction: column">
      <div class="mapTable" style="top: 50px" v-show="leftTable">
        <h5>左上map：</h5>
        <Tree :data="leftTopTree" :load-data="loadDataLeft"   show-checkbox  @on-select-change="onSelectChange" @on-check-change="onCheckChange"></Tree>
      </div>
      <div class="mapTable" :style="{top:rightTableTop}" v-show="rightTable">
        <h5>右下map：</h5>
        <Tree :data="rightTopTree" :load-data="loadDataRight"   show-checkbox  @on-select-change="onSelectChangeRight" @on-check-change="onCheckChangeRight"></Tree>
      </div>
    </div>

<!-- 地图 -->
    <div style="position: relative;height: 100%">
      <div id="beforedqmapBox" ref="themap" class="map"></div>
      <div id="dqmapBox" ref="themap" class="map"></div>
      <div id="wrapper"></div>
    </div>


  </div>
</template>

<script>

/*
* 图层
* */
const map = {
  data() {
    return{
      map: null,
      leftMap:null,
      mapbox:true,
      comp:null,  // 卷帘对象
      leftTop: true
    }
  },
  methods: {
    // 右侧地图
    initMap() {
      let that = this;
      this.map = new mapboxgl.Map({
        container: "dqmapBox", // container id
        style: "./static/map/map.json",
        // simple, //四维地球
        // "http://121.36.21.73:20002/api/pie-cloud/layerData/layerTemplates?id=2c92808c71bafa7a01720c80d12f010c&key=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpbmZvIjoie1widXNlcklkXCI6XCIxMDFcIixcImtleVwiOlwiOTBjNGI5NDI0N2FiMThmYmRiZTMyZDc4NzBkMTVjN2JcIn0ifQ.ifWlOcwmtenARlro-tf9hdLDlXjmbIa2T5AwSvRQB-M", // stylesheet location
        center: [116.4, 34.5],
        zoom: 3, // starting zoom
        minZoom: 3,
        epsg: 3857,
        attributionControl: true,
        doubleClickZoom: false,
      });
    },
    initLeft() {
      let that = this;
      this.leftMap = new mapboxgl.Map({
        container: "beforedqmapBox", // container id
        style:  './static/map/map.json',
        // simple, //四维地球
        // "http://121.36.21.73:20002/api/pie-cloud/layerData/layerTemplates?id=2c92808c71bafa7a01720c80d12f010c&key=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpbmZvIjoie1widXNlcklkXCI6XCIxMDFcIixcImtleVwiOlwiOTBjNGI5NDI0N2FiMThmYmRiZTMyZDc4NzBkMTVjN2JcIn0ifQ.ifWlOcwmtenARlro-tf9hdLDlXjmbIa2T5AwSvRQB-M", // stylesheet location
        center: [116.4, 34.5],
        zoom: 3, // starting zoom
        minZoom: 3,
        epsg: 3857,
        attributionControl: true,
        doubleClickZoom: false,
      });
    },



    // 初始化 卷帘
    initSwit(data,firm) {
      let that=this
      this.comp = new mapboxgl.Compare(
          that.leftMap,
          that.map,
          "#wrapper",
          {
            orientation:data?data: "vertical"
          }
      );
      if (firm) return
      this.comp.setSlider(2222);
      let selectDom = document.getElementById("wrapper");
      selectDom.style.display="none"
    },

    changeRange() {
      if (this.comp){
        this.leftTop = !this.leftTop;
        let data = this.comp.options.orientation==="vertical"?"horizontal":"vertical";
        this.comp.remove();
        this.initSwit(data,true);
      }
    },

    // 打开关闭卷帘。
    showMap(data) {
      if (!this.comp)return
      let selectDom = document.getElementById("wrapper");
      let box = document.querySelector(".mapbox");
      let compSelect=this.comp.options.orientation
      if (data==="left") {
        this.comp.setSlider(0);
        selectDom.style.display="none"
        this.leftTable=false
        this.rightTable=true
      }else if (data==="right"){
        this.comp.setSlider(2222);
        selectDom.style.display="none"
        this.leftTable=true
        this.rightTable=false
      }else{
        if (compSelect==="vertical") {
         let num= parseInt(getComputedStyle(box , null)["width"]);
          this.comp.setSlider(parseInt(num/2));
        }else {
          let num= parseInt(getComputedStyle(box , null)["height"]);
          this.comp.setSlider(parseInt(num/2));
        }
        this.leftTable=true
        this.rightTable=true
        selectDom.style.display="block"
      }
    },


    //添加图层服务
    addSouresLary( current,mapName) {
      let that = this;
      let tile
      if (current.serviceUrl) {
        // 底图服务
        tile = mapServeUrl + current.serviceUrl;
      }else{
        //影像服务
        tile = mapServeUrl + "/image-server/v1" + '?request=GetTile&TILECOL={x}&TILEROW={y}&TILEMATRIX={z}&info={"info":' +
            JSON.stringify([{path: current.path, style:{ stretch:{externalNodataValue:0} }}])+"}";
      }

      this[mapName].addSource(current.title+"#"+current.nodeKey, {
        type: "raster",
        tiles: [tile],
        tileSize: 256,
      });
      let videoLayer = {
        id: current.title+"#"+current.nodeKey,
        type: "raster",
        source: current.title+"#"+current.nodeKey,
       /* minzoom: current.minRatio,
        maxzoom: current.maxRatio,*/
        paint: {
          "raster-opacity": 1,
        },
      };
      this[mapName].addLayer(videoLayer);
    },


    // 查找是否存在源和图层
    findMapZy(id,lOR) {
      if (lOR==="left"){
        if (this.leftMap.getLayer(id)&&this.leftMap.getSource(id)) {
          return true
        }else {
          return false
        }
      }else {
        if (this.map.getLayer(id)&&this.map.getSource(id)) {
          return true
        }else {
          return false
        }
      }
    },


    // 清除图层和元数据
    clearLeftMap(id,lOR) {
      if (lOR==="left"){
        if (this.leftMap.getLayer(id)) {
          this.leftMap.removeLayer(id);
        }
        if (this.leftMap.getSource(id)) {
          this.leftMap.removeSource(id);
        }
      }else {
        if (this.map.getLayer(id)) {
          this.map.removeLayer(id);
        }
        if (this.map.getSource(id)) {
          this.map.removeSource(id);
        }
      }
    },
  },
};

const table = {
  data() {
    return{
      changeDeagle:false,
      tableShow: true,
      leftTable: true,
      rightTable: false,
      rightTableTop:"400px"
    }
  },
  methods: {
    // 打开图层
    openChange() {
      this.changeDeagle = !this.changeDeagle;
      this.$nextTick(()=>{
        if (this.changeDeagle) {   // 打开弹框
          this.initMap();
          this.initLeft();
          this.initSwit();
        }else{
          this.comp.remove()
          this.map = null;
          this.leftMap = null;
        }
      })
    },
  },

  watch:{
    leftTable(newData) {
      if (newData) {
        this.rightTableTop = "400px";
      }else {
        this.rightTableTop = "50px";
      }
    }
  }
};

const leftTree={
  data() {
    return{
      leftTopTree: [
        {
          title: '算法',
          loading: false,
          expand:true,
          children: [
            {
              title: '当前算法',
              expand:true,
              loading: false,
              children: []
            },

          ]
        },
        {
          title: '影像',
          loading: false,
          expand:true,
          children: []
        }
      ],
      treeList: [],
      rightTopTree: [
        {
          title: '算法',
          loading: false,
          expand:true,
          children: [
            {
              title: '当前算法',
              expand:true,
              loading: false,
              children: []
            },
          ]
        },
        {
          title: '影像',
          loading: false,
          expand:true,
          children: []
        }
      ],
    }
  },
  mounted() {
    // 获取图层
    this.layerManage();
    // 获取影像
    this.$bus.$on("fileList" ,(inputFileList,outputFileList)=>{
      // 添加title
      inputFileList.forEach((item)=>{
        item.title = item.name;
      })
      outputFileList.forEach((item)=>{
        item.title = item.name;
      })
      let data=[
        {
          title: '影像输入',
          loading: false,
          children: inputFileList
        },
        {
          title: '影像输出',
          loading: false,
          children: outputFileList
        },
      ]
      this.$set(this.leftTopTree[0].children[0],"children",JSON.parse(JSON.stringify(data)))
      this.$set(this.rightTopTree[0].children[0],"children",JSON.parse(JSON.stringify(data)))
    })
  },
  methods: {
    // 获取拍平的数组
    getArray(data) {
      if (!(data instanceof Array))return
      data.forEach((item)=>{
        if (item.children) {
          this.getArray(item.children);
        }else {
          this.treeList.push(item)
        }
      })
    },
    layerManage() {
     let treefather = [];
      let path = this.$api.dataOptimizationApi.imageClassifyInfo;
      this.http.get(path).then((res) => {
        if (res.data.success) {
          res.data.data.forEach((item) => {
            this.childrendata = [];
            item.children.forEach((data) => {
              let cName = data.name;
              let Cnname = {
                title: data.name,
                serviceUrl: data.serviceUrl,
                id: data.id,
                minRatio: data.minRatio,
                maxRatio: data.maxRatio,
              };
              if (data.isRelease) {
                this.childrendata.push(Cnname);
              }
            });
            let itemdata = {
              title: item.imageClassifyName,
              pid: item.id,
              children: this.childrendata,
            };
            treefather.push(itemdata);
            this.$set(this.leftTopTree[1],"children",JSON.parse(JSON.stringify(treefather)))
            this.$set(this.rightTopTree[1],"children",JSON.parse(JSON.stringify(treefather)))
          });
        } else {
          this.$Message.error(res.data.message);
        }
      });
    },
    /* 左右侧懒加载 */
    loadDataLeft (item, callback) {
      /*
      * load-data 第一个参数为当前节点信息；执行 load-data 的第二个参数，将需要添加的数据传入。如果某节点不包含 loading 和 children 字段，则不会应用异步加载效果。
      * */
        callback("data");
    },
    loadDataRight (item, callback) {
      /*
      * load-data 第一个参数为当前节点信息；执行 load-data 的第二个参数，将需要添加的数据传入。如果某节点不包含 loading 和 children 字段，则不会应用异步加载效果。
      * */
      callback("data");
    },




    /*
    * 左侧树操作
    * */
    // tree  的 select
    onSelectChange(selectNode,currentNode){
      this.leftMap.moveLayer(currentNode.title+"#"+currentNode.nodeKey);
    },
    // tree  的 点击
    onCheckChange(selectNode,currentNode) {
      if (currentNode.checked) {  // 选中
        if (!currentNode.children){  // 选中最后以及
          this.addSouresLary(currentNode,"leftMap")
        }else {
          this.treeList = [];
          this.getArray(currentNode.children)
          this.treeList.forEach((item)=>{      // 批量选择
            if (!item.children&& item.checked) {
              this.addSouresLary(item,"leftMap")
            }
          })
        }
      }else {  // 取消选中
        if (!currentNode.children){  // 选中最后以及
          this.clearLeftMap(currentNode.title+"#"+currentNode.nodeKey,"left")
        }else {
          this.treeList = [];
          this.getArray(currentNode.children)
          this.treeList.forEach((item)=>{    //  批量选择
            if (!item.children&& this.findMapZy(item.title+"#"+item.nodeKey,"left")) {
              this.clearLeftMap(item.title+"#"+item.nodeKey,"left")
            }
          })
        }
      }
    },

    /*
    * 右侧树操作
    * */
    // tree  的 select
    onSelectChangeRight(selectNode,currentNode){
      // this.map.setPaintProperty(currentNode.title+"#"+currentNode.nodeKey, 'raster-opacity', 0);
      this.map.moveLayer(currentNode.title+"#"+currentNode.nodeKey );
    },
    // tree  的 点击
    onCheckChangeRight(selectNode,currentNode) {
      if (currentNode.checked) {  // 选中
        if (!currentNode.children){  // 选中最后以及
          this.addSouresLary(currentNode,"map")
        }else {
          this.treeList = [];
          this.getArray(currentNode.children)
          this.treeList.forEach((item)=>{      // 批量选择
            if (!item.children&& item.checked) {
              this.addSouresLary(item,"map")
            }
          })
        }
      }else {  // 取消选中
        if (!currentNode.children){  // 选中最后以及
          this.clearLeftMap(currentNode.title+"#"+currentNode.nodeKey,"right")
        }else {
          this.treeList = [];
          this.getArray(currentNode.children)
          this.treeList.forEach((item)=>{    //  批量选择
            if (!item.children&& this.findMapZy(item.title+"#"+item.nodeKey,"right")) {
              this.clearLeftMap(item.title+"#"+item.nodeKey,"right")
            }
          })
        }
      }
    }
  }
}
export default {
  name: "mapCompereDetal",
  mixins: [map,table,leftTree],
}


</script>

<style scoped>
.mapbox {
  width:100%;
  height: 100%;
  position: absolute;
  z-index: 100;
  cursor: pointer;
}
.map {
  position: absolute;
  top: 0;
  bottom: 0;
  width: 100%;
  height: calc(100vh - 80px);
  cursor: pointer;
}


.mapTable{
  position: absolute;
  left: 10px;
  z-index: 200;
  width:400px;
  padding: 10px;
  height: 300px;
  overflow-y: auto;
  background-color: rgba(34,123,45,0.6);
  border-radius: 5px
}




</style>


<style scoped>
/deep/.ivu-tree {
  color: white;
}
/deep/.ivu-tree-title{
  color: white;
}
/deep/.mapboxgl-compare{
background-color: rgba(0,0,0,0);
}

/deep/ .ivu-table {
  color: white;
  background-color: rgba(0, 0, 0, 0) !important;
}
/deep/.ivu-table:before, .ivu-table:after{
  background-color: rgba(0, 0, 0, 0)!important;
}
/deep/.ivu-table td, .ivu-table th{
  background-color: rgba(0, 0, 0, 0)!important;
}
/deep/.ivu-poptip-popper{

  left: 55px!important;
}

</style>